<?php
namespace app\index\controller;
use szktor\Random;
use szktor\Pinyin;
use szktor\Alioss;
use think\captcha\Captcha;
use think\facade\Cache;
use think\facade\Env;
use think\facade\Url;
use think\facade\Session;
use app\common\model\ClinicAdmin;
use app\common\model\Clinic;
use app\common\model\AuthRule;
use app\common\model\SystemAttachment;
use app\common\model\SystemAttachmentCategory;
use app\common\model\ClinicAdminMessage;
/*
* 前台-iframe主页
*/
class Index extends BaseIndex
{
    protected $noNeedLogin = ['login','logout','captcha','send_phone_verify'];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = [
		'index','wipecache','search','upload_excel',
		//附件操作
		'attachment', 'set_attachment_cate','del_attachment_cate','load_attachment_cate_list','load_attachment_list','del_attachment'
	];  //无需鉴权的方法，但需要登录
	
	//主页
    public function index()
    {
		//工作台页面
		$homeUrl = !$this->admin['index_page'] ? Url::build('index/home/index') : Url::build($this->admin['index_page']);
		$this->assign([
			'home_url' => $homeUrl,
			//当前人员未读消息 总数
			'msg_no_read_count' => ClinicAdminMessage::getMessageCount($this->admin['id'],'','0'),
		]);
        return $this->view->fetch();
	}
	//主页菜单功能搜索
    public function search($word = '')
    {
    	if($this->request->isPost() || $this->request->isAjax())
		{
			$data = $this->request->only(['searchword','page'],'post');
			if (!$data['searchword']) {
			    return json(['err' => '1', 'msg' => '当前页下的数据已显示完毕！']);
		    }
			//条件
			$map = [
				['module_type','=','index_menu'],
				['status','=','1'],
				['type','=','menu'],
	            ['title|url','like','%' . $data['searchword'] . '%'],
			];
			//管理员权限
			//$adminRules = _getCurrAdminRules($this->admin, $this->clinic);
		    $adminRules = isset($this->admin['rules_check_res']) ? $this->admin['rules_check_res'] : ['-100'];
		    if($adminRules)
		    {
		    	$map[] = ['id','in',implode(',',array_unique($adminRules))];
		    }
			$this->pageNum = 15;
			$limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
			$list = AuthRule::where($map)->field('id,title,url,icon,remark,create_time')
			        ->order('sort desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
			if (count($list) <= 0) {
				return json(['err' => '2', 'msg' => '当前页下的数据已显示完毕！']);
			}
			foreach($list as $k => &$v)
			{
				$v['url'] = Url::build($v['url']);
			}
			return json([
				'err' => '0',
				'page' => $list->currentPage(),
				'limit' => $limit,
				'total' => $list->total(),
				'list' => $list->items(),
			]);
		}
		if(!$word)
		{
            return $this->redirect($this->admin['index_page'], '', 302);
		}
		$this->assign([
			'word' => $word,
		]);
        return $this->view->fetch();
	}

    /**
     * 全局Excel上传管理 index/index/upload_excel
    */
    public function upload_excel()
    {
		if(!$this->request->isPost())
		{
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
		}
		try
        {
            $savedir = trim($this->request->post('savedir'));
            $inputname = trim($this->request->post('inputname'));
            $inputname = !$inputname ? 'file' : $inputname;
            //重新定义 保存的目录
			$clinicDir = 'attachment_clinic_' . $this->admin['clinic_id'];
			$clinicPath = Env::get('root_path') . "public" . DS . "upload" . DS . $clinicDir;
			if(!is_dir($clinicPath))
			{
				mkdir($clinicPath, 0777);
				chmod($clinicPath, 0777);
			}
            if($savedir)
            {
                $path = Env::get('root_path') . "public" . DS . "upload" . DS . $clinicDir . DS . strtolower($savedir);
                $pathUrl = "/upload/" . $clinicDir . "/" . strtolower($savedir). "/";
                $imgUrl = $this->site['weburl'] . "/" . "upload/" . $clinicDir . "/" . strtolower($savedir) . "/";
            }else{
                $path = Env::get('root_path') . "public".DS."upload".DS.$clinicDir;
                $pathUrl = "/upload/" . $clinicDir . "/";
                $imgUrl = $this->site['weburl'] . "/" . "upload/" . $clinicDir . "/";
            }
            if(!is_dir($path))
            {
                mkdir($path, 0777);
                chmod($path, 0777);
            }
            $files = $this->request->file($inputname);
            $infos = $files->validate(['ext' => 'xls,xlsx'])->move($path);
            if($infos)
            {
                $save_name = str_replace("\\",'/',$infos->getSaveName());
                $res = [
                    'err' => '0',
                    'path' => $pathUrl . $save_name, //返回文件保存的路径
                    'url' => $imgUrl . $save_name, //返回文件web url
                ];
                return json($res);
            } else {
                return json(['err' => '1','msg' => $files->getError()]);
            }
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
	}
	/**
     * 全局附件上传管理 index/index/attachment.html?multiple=0
     * $multiple = 0 单选，$multiple = 1 多选 
	 * backfun 选择后默认回调函数名
    */
    public function attachment($multiple = 0, $backfun = 'selectAttachmentFun')
    {
		if($this->request->isPost() || $this->request->isAjax())
		{
			$savedir = trim($this->request->post('savedir'));
			$inputname = trim($this->request->post('inputname'));
			$cateId = intval($this->request->post('cate_id'));
			$inputname = !$inputname ? 'file' : $inputname;
			//重新定义 保存的目录
			$clinicDir = 'attachment_clinic_' . $this->admin['clinic_id'];
			$clinicPath = Env::get('root_path') . "public" . DS . "upload" . DS . $clinicDir;
			if(!is_dir($clinicPath))
			{
				mkdir($clinicPath, 0777);
				chmod($clinicPath, 0777);
			}
			if($savedir)
			{
				$aliOssPath = "upload/" . $clinicDir . '/' . strtolower($savedir);
				$path = Env::get('root_path') . "public" . DS . "upload" . DS . $clinicDir . DS .strtolower($savedir);
				$pathUrl = "/upload/" . $clinicDir . "/" . strtolower($savedir) . "/";
				$imgUrl = $this->site['weburl'] . "/" . "upload/" . $clinicDir . "/" . strtolower($savedir) . "/";
			}else{
				$aliOssPath = "upload";
				$path = Env::get('root_path') . "public" . DS . "upload";
				$pathUrl = "/upload" . $clinicDir . "/";
				$imgUrl = $this->site['weburl'] . "/" . "upload" . $clinicDir . "/";
			}
			if(!is_dir($path))
			{
				mkdir($path, 0777);
				chmod($path, 0777);
			}
			$files = $this->request->file($inputname);
			if (!$files) {
				return json(['err' => '1', 'msg' => '上传的文件无效或不存在']);
			}
			$infos = $files->validate(['ext' => 'jpg,png,gif,jpeg,bmp'])->move($path);
			if($infos)
			{
				$saveName = str_replace("\\",'/',$infos->getSaveName());
				$res = [
					'err' => '0',
					'msg' => '文件上传成功',
					'img_path' => $pathUrl . $saveName, //返回文件保存的路径
					'img_url' => $imgUrl . $saveName, //返回文件web url
					'oss_url' => '', //阿里云OSS url
					'sqlinfo' => [], //保存的附件信息
				];
				//获取文件信息
				$fileInfo = $infos->getInfo();
				$sqlData = [
					'clinic_id' => $this->admin['clinic_id'], //诊所门店表的id
					'admin_id' => $this->admin['id'], //诊所门店表的adminid
					'name' => isset($fileInfo['name']) ? $fileInfo['name'] : '', //附件名称
					'att_dir' => $res['img_path'], //附件路径
					'satt_dir' => '', //压缩图片路径
					'att_size' => isset($fileInfo['size']) ? $fileInfo['size'] : '', //附件大小
					'att_type' => isset($fileInfo['type']) ? $fileInfo['type'] : '', //附件类型
					'cate_id' => $cateId, //分类ID，0=默认分类
					'create_time' => time(), //上传时间
					'image_type' => '1', //图片上传类型 1本地 2七牛云 3OSS 4COS 
					'soure_type' => '1', //图片上传来源类型 1 后台上传 2 用户生成 3 微信上传
					'real_name' => isset($fileInfo['tmp_name']) ? $fileInfo['tmp_name'] : '', //原始文件名
				];
				$rid = SystemAttachment::insertGetId($sqlData);
				//文件类型判断
			    $typeTxt = '未知';
				if($sqlData['att_type'])
				{
					$typeTxt = preg_replace('#image\/#','',trim($sqlData['att_type']));
				}
			    //大小获取
			    $sqlData['image_type_txt'] = $typeTxt . '，' . _formatFileSize($sqlData['att_size'],1);
				$res['sqlinfo'] = $sqlData;
				$res['sqlinfo']['id'] = $rid;
				//上传至阿里云OSS
				if(intval($this->ossConfig['up_alioss_onoff']) > 0)
				{
					$oss = Alioss::instance($this->ossConfig);
					$ossRes = $oss->uploadAliOssSimple($aliOssPath.'/'.$save_name,$path.'/'.$save_name);
					//上传出错写下日志
					if(isset($ossRes['err']) && (int)$ossRes['err'] <= 0)
					{
					  $res['oss_url'] = trim($ossRes['oss_url']);
					}else{
					  _writeSystemLog($ossRes);
					}
				}
				return json($res);
			} else {
				return json(['err' => '1','msg' => '上传出错：' . $files->getError()]);
			}
		}
		$this->assign([
			'is_multiple' => intval($multiple),
			'back_fun_name' => trim($backfun),
		]);
		return $this->view->fetch();
	}
    /**
     * 加载附件分类下的图片 index/index/load_attachment_list
    */
    public function load_attachment_list()
    {
		if(!$this->request->isAjax())
		{
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
		}
		$data = $this->request->only(['cateid','page'],'post');
		//条件
		$map = [['clinic_id','=',$this->admin['clinic_id']]];
		if((int)$this->admin['is_supper_admin'] <= 0)
		{
			$map[] = ['admin_id','=',$this->admin['id']];
		}
		if(intval($data['cateid']) > 0)
		{
			$map[] = ['cate_id','=',intval($data['cateid'])];
		}
		$limit = intval($this->pageNum) > 0 ? intval($this->pageNum) : 20;
		$list = SystemAttachment::where($map)->field('id,name,att_dir,satt_dir,att_size,att_type,cate_id,create_time,image_type,soure_type,real_name')
		        ->order('create_time desc')->paginate($limit,false,['page' => $data['page'], 'var_page' => 'page']);
		if (count($list) <= 0) {
			return json(['err' => '2', 'msg' => '当前页下的数据已显示完毕！']);
		}
		$res = ['err' => '0', 'page' => $list->currentPage(), 'limit' => $limit, 'total' => $list->total(), 'list' => $list->items()];
		foreach ($res['list'] as $key => &$val) {
			//文件类型判断
			$typeTxt = '未知';
			if($val['att_type'])
			{
				$typeTxt = preg_replace('#image\/#','',trim($val['att_type']));
			}
			//大小获取
			$val['image_type_txt'] = $typeTxt . '，' . _formatFileSize($val['att_size'],1);
		}
		return json($res);
	}
    /**
     * 删除附件分类下的图片
    */
    public function del_attachment()
    {
		if(!$this->request->isAjax())
		{
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
		}
		$data = $this->request->only(['id']);
		if(intval($data['id']) <= 0){
			return json(['err' => '2', 'msg' => '参数错误，请重试']);
		}
		//条件
		$map = [['id','=',intval($data['id'])],['clinic_id','=',$this->admin['clinic_id']]];
		if((int)$this->admin['is_supper_admin'] <= 0)
		{
			$map[] = ['admin_id','=',$this->admin['id']];
		}
		$info = SystemAttachment::where($map)->field('id,att_dir')->find();
		if(!$info || !isset($info['id']) || intval($info['id']) <= 0)
		{
			return json(['err' => '3', 'msg' => '删除失败，请重试']);
		}
		$path = $info['att_dir'];
		if(substr($path,0,1) != '/') $path = '/'.$path;
		$path = Env::get('root_path') . "public" . $path;
		$r = @unlink($path);
		if(!$r) return json(['err' => '4', 'msg' => '图片删除失败']);
		SystemAttachment::where(['id' => $info['id']])->delete();
		return json(['err' => '0', 'msg' => '图片删除成功']);
	}
	/**
     * 加载所有附件分类 index/index/load_attachment_cate_list
    */
    public function load_attachment_cate_list()
    {
		if(!$this->request->isAjax())
		{
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
		}
		$map = [['clinic_id','=',$this->admin['clinic_id']]];
		if((int)$this->admin['is_supper_admin'] <= 0)
		{
			$map[] = ['admin_id','=',$this->admin['id']];
		}
		$list = SystemAttachmentCategory::where(['clinic_id' => $this->admin['clinic_id']])->order('sort desc')->select();
		if(count($list) <= 0)
		{
            return json(['err' => '2', 'msg' => '暂无分类，请先添加']);
		}
		return json(['err' => '0', 'msg' => '加载分类成功', 'list' => $list->toArray()]);
	}
	/**
     * 全局设置附件分类 index/index/set_attachment_cate
    */
    public function set_attachment_cate()
    {
		if(!$this->request->isAjax())
		{
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
		}
		$data = $this->request->only(['id','name','sort']);
		if(!($data['name'])){
			return json(['err' => '2', 'msg' => '分类名称不能为空']);
		}
		try
		{
			$sqlData = [
				'clinic_id' => $this->admin['clinic_id'], //诊所门店表的id
				'admin_id' => $this->admin['id'], //诊所门店表的adminid
				'name' => trim($data['name']), //分类名称
				'enname' => Pinyin::get($data['name'],true), //分类英文名
				'sort' => intval($data['sort']), //数值越大越靠前显示
			];
			if(intval($data['id']) > 0)
			{
				unset($sqlData['clinic_id']);
				$r = SystemAttachmentCategory::where(['id' => intval($data['id']), 'clinic_id' => $this->admin['clinic_id']])->update($sqlData);
			}else{
				$r = SystemAttachmentCategory::insert($sqlData);
			}
			if($r)
			{
				return json(['err' => '0', 'msg' => '分类信息保存成功']);
			}else{
				return json(['err' => '3', 'msg' => '保存失败']);
			}
		}catch (\think\Exception $e){ // use think\Exception;
		   return ['err' => '4', 'msg' => '失败：' . $e->getMessage()];
		}
	}
	/**
     * 删除附件分类 index/index/del_attachment_cate
    */
    public function del_attachment_cate()
    {
		if(!$this->request->isAjax())
		{
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
		}
		$data = $this->request->only(['id']);
		if(intval($data['id']) <= 0){
			return json(['err' => '2', 'msg' => '参数错误，请重试']);
		}
		SystemAttachmentCategory::beginTrans();
		try
		{
			$map1 = [
				['id','=',intval($data['id'])],
				['clinic_id','=',$this->admin['clinic_id']],
			];
			$map2 = [
				['cate_id','=',intval($data['id'])],
				['clinic_id','=',$this->admin['clinic_id']],
			];
			if((int)$this->admin['is_supper_admin'] <= 0)
			{
				$map1[] = ['admin_id','=',$this->admin['id']];
				$map2[] = ['admin_id','=',$this->admin['id']];
			}
			$r1 = SystemAttachmentCategory::where($map1)->delete();
			$r2 = SystemAttachment::where($map2)->update(['cate_id'=> '0']);
			SystemAttachmentCategory::commitTrans(); 
			return json(['err' => '0', 'msg' => '分类删除成功']);
		}catch (\think\Exception $e){ // use think\Exception;
		   SystemAttachmentCategory::rollbackTrans();
		   return ['err' => '4', 'msg' => '失败：' . $e->getMessage()];
		}
	}
	//清理缓存 /index/index/wipecache.html
    public function wipecache()
    {
		$res = __clearnSystemCache();
        if ($res) {
            return json(['err' => '0', 'msg' => '已成功清除系统缓存！']);
        } else {
            return json(['err' => '0', 'msg' => '清除缓存失败!']);
        }
	}
	//登录+注册发送手机验证码
    public function send_phone_verify()
    {
		if(!$this->request->isAjax())
		{
			return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
		}
		$data = $this->request->only(['tel','captcha','captcha_key']);
		if(!captcha_check($data['captcha'],$data['captcha_key'])){
			return json(['err' => '2', 'msg' => '对不起，图形验证码输入错误']);
		}
		//准备向手机号码发送验证码
		$number = Random::numeric(5); //5位数字
		$chName = md5($this->site['cookie_pre'] . 'sms_send_code_' . $data['tel']);
		$body = '您的验证码是' . $number . '，5分钟内有效';
		_writeSystemLog($data['tel'] . ':' . $body);
		$res = _sendSMSMessage($data['tel'],$body);
		if((int)$res['err'] > 0)
		{
			//发送失败
			return json($res);
		}
		Session::set($chName,json_encode(['num' => $number, 'exp' => time()+300]));
		return json(['err' => '0', 'msg' => '手机验证码已发送成功']);
	}
	//图形验证码
    public function captcha($soure = '', $key = '1')
    {
		$config =    [
			// 验证码字体大小
			'fontSize'    =>    60,    
			// 验证码位数
			'length'      =>    4,   
			// 关闭验证码杂点
			'useNoise'    =>    true,
			//设置验证码字符为纯数字
			'codeSet'     =>    '01G2B34R56K789T',
		];
		$captcha = new Captcha($config);
		return $captcha->entry($key);
	}
	//用户登录 - 登录方式 0=账号登录, 1=免密登录, 2=微信扫码登录
    public function login($backurl = '')
    {
		if($this->request->isAjax())
		{
			$data = $this->request->only(['back_url','loginmode','name','pwd','tel','captcha','captcha_key','code']);
			//总店编码
			$mallCode = '';
			
			if($data['loginmode'] == 0) //0=账号登录
			{
				$res = $this->auth->login($data['name'], $data['pwd']);
			}
			if($data['loginmode'] == 1) //1=免密登录
			{
				if(!captcha_check($data['captcha'],$data['captcha_key'])){
					return json(['err' => '1', 'msg' => '对不起，图形验证码输入错误']);
				}
				//1.检查手机号对应的验证码是否正确
				$chName = md5($this->site['cookie_pre'] . 'sms_send_code_' . $data['tel']);
				$yzmRes = Session::get($chName);
				if($yzmRes) $yzmRes = json_decode($yzmRes,true);
				if(!$yzmRes || !isset($yzmRes['num']) || (isset($yzmRes['exp']) && time() > $yzmRes['exp']))
				{
					return json(['err' => '2', 'msg' => '手机验证码已失效，请重新获取']);
				}
				if(empty($data['code']) || $data['code'] != $yzmRes['num'] || empty($yzmRes['num']))
				{
					return json(['err' => '2', 'msg' => '对不起，手机验证码不正确']);
				}
				Session::delete($chName);
				//2.执行登录 或 注册 新账户
                $res = $this->auth->loginAndRegister($data['tel'],$mallCode);
			}
			if($data['loginmode'] == 2) //2=微信扫码登录
			{
				return json(['err' => '2', 'msg' => '对不起，此功能暂未开放']);
			}
			if((int)$res['err'] > 0) return json($res);
			$redirectUri = !$data['back_url'] ? Url::build('index/index/index') : urldecode($data['back_url']);
			return json(['err' => '0', 'msg' => '登录成功，请稍候...', 'url' => $redirectUri]);
		}else{
			if($this->admin)
			{
				$backurl = urldecode($backurl);
				$backurl = !$backurl ? Url::build('index/index/index') : trim($backurl);
				return $this->redirect($backurl, '', 302);
				//return $this->success("您已登录，请勿重复登录！", $this->request->get('url', $backurl));
			}
			$backurl = Url::build('index/index/index');
			$this->assign([
				'captcha_key' => md5($this->site['client_uuid'] . '_1'),
				'back_url' => $backurl
			]);
			return $this->view->fetch();
		}
	}
	//用户退出登录
    public function logout()
    {
		$r1 = $this->auth->logout();
		return $this->redirect(Url::build('index/index/login'), '', 302);
	}
}
